<template>
  <div v-loading="submitLoading" element-loading-text="处理中，请稍后...">
    <div style="margin-top: 100px; padding-bottom: 100px">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="200px"
        style="width: 600px; margin: 0 auto"
      >
        <el-row :gutter="15">
          <!-- <el-col :span="24">
            <el-form-item label="申请单位" prop="unitHospitalName">
              <el-input
                v-model="form.unitHospitalName"
                placeholder="请输入申请单位"
                style="width: 100%"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="学员姓名" prop="applicantName">
              <el-input
                v-model="form.applicantName"
                placeholder="请输入学员姓名"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="form.phoneNumber"
                placeholder="请输入手机号码"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="进修科目" prop="registerDeptId">
              <el-select
                v-model="form.registerDeptId"
                placeholder="请选择进修科目"
                filterable
                clearable
                @change="getInfo"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in registerDeptList"
                  :key="index"
                  :label="item.registerDeptName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="进修批次"
              prop="batchName"
              v-if="form.registerDeptId"
            >
              <div class="batch-select-wrapper">
                <el-select
                  class="batch-select"
                  v-model="form.batchName"
                  placeholder="请选择招生批次"
                  filterable
                  clearable
                  @change="batchNameChange"
                >
                  <el-option
                    v-for="(item, index) in batchNameList"
                    :key="index"
                    :disabled="item.useStatus === false"
                    :label="
                      (item.year ? item.year + '年' : '') +
                      item.name +
                      '份批次' +
                      (item.useStatus === false
                        ? '（不在报名时间范围）'
                        : '')
                    "
                    :value="item.name"
                  />
                </el-select>
                <div class="batch-deadline-tip" v-if="alertMsg">
                  <i class="el-icon-time"></i>
                  <span>{{ alertMsg }}</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.registerDeptId">
            <el-form-item label="进修期限" prop="durationName">
              <el-radio-group
                v-model="form.durationName"
                @change="durationNameChange"
              >
                <el-radio
                  v-for="(item, index) in durationNameList"
                  :key="index"
                  :label="item.name"
                  >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.registerDeptId">
            <el-form-item label="进修时间" prop="durationStartDate">
              <span v-if="durationDateList.length > 0"
                >{{ durationDateList[0] }} - {{ durationDateList[1] }}</span
              >
              <span v-else>不限</span>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <div style="display: flex; align-items: flex-start">
              <el-form-item label="进修开始时间" prop="durationStartDate">
                <el-date-picker
                  v-model="form.durationStartDate"
                  :type="'month'"
                  :format="'yyyy/MM'"
                  :value-format="'yyyy/MM'"
                  @change="durationStartDateChange"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="" label-width="20px" prop="durationEndDate">
                <el-date-picker
                  v-model="form.durationEndDate"
                  :type="'month'"
                  :format="'yyyy/MM'"
                  :value-format="'yyyy/MM'"
                  :disabled="true"
                >
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col> -->
        </el-row>

        <div class="bottom-box">
          <!-- <el-button type="primary" plain @click="stopForm">暂 存</el-button> -->
          <el-button type="primary" @click="noticeShow = true">提交</el-button>
        </div>
      </el-form>
    </div>

    <!-- 提交报名 -->
    <el-dialog
      class="notice"
      :visible.sync="noticeShow"
      width="600px"
      center
      :close-on-click-modal="false"
    >
      <div slot="title" class="title">系统提示</div>
      <div class="content">
        <img src="@/assets/images/notice.png" width="100px" height="100px" />
        <div style="font-weight: bolder">
          请确认所有填报信息和上传附件准确完整
        </div>
        <div>确保所填信息真实有效</div>
      </div>
      <div slot="footer">
        <el-button
          type="primary"
          plain
          @click="
            noticeShow = false;
            submitLoading = false;
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm">确 认</el-button>
      </div>
    </el-dialog>

    <el-dialog
      class="notice"
      :visible.sync="finishShow"
      width="600px"
      center
      :close-on-click-modal="false"
    >
      <div slot="title" class="title">系统提示</div>
      <div class="content">
        <i class="el-icon-success" style="font-size: 68px; color: #67c23a"></i>
        <div style="font-weight: bolder">提交成功</div>
        <div>在我的“个人中心---我的申请”中可查看审批进度</div>
        <div>请您持续关注~</div>
      </div>
      <div slot="footer">
        <el-button type="primary" plain @click="finishCancel">取 消</el-button>
        <el-button type="primary" @click="finishSuccess">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import { listAllRegisterDept } from "@/api/business/registerDept";
import {
  agentRegisterInfo,
  getRegisterInfo,
} from "@/api/business/registerInfo";
import { listRegisterNeed } from "@/api/business/registerNeed";
import { isEmpty } from "@/utils/validate";
export default {
  name: "registerInfoUpdateNginx",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      currYear: new Date().getFullYear(),
      stepActive: 2,
      // 表单参数
      batchList: [],
      batchNameList: [],
      batchNameObj: null,
      durationNameList: [],
      alertMsg: "",
      // 进修期限类型 1-按月 2-按日
      durationNameType: 1,
      durationDateList: [],
      registerDeptList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      // 表单参数
      form: {
        phoneNumber: "",
        applicantName: "",
        unitHospitalName: "",
        registerDeptName: "",
        registerDeptId: "",
        educationType: "个人进修",
        durationStartDate: "",
        durationName: "",
        durationMoney: 0,
        durationEndDate: "",
        batchName: "",
        batchDate: "",
      },
      // 表单校验
      rules: {
        agentUserId: [
          {
            required: true,
            message: "代理申请用户ID不能为空",
            trigger: ["blur", "change"],
          },
        ],
        registerDeptId: [
          {
            required: true,
            message: "进修科目不能为空",
            trigger: ["blur", "change"],
          },
        ],
        registerNeedId: [
          {
            required: true,
            message: "招生信息ID不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitHospitalName: [
          { required: true, message: "不能为空", trigger: ["blur", "change"] },
        ],
        applicantName: [
          {
            required: true,
            message: "申请人姓名不能为空",
            trigger: ["blur", "change"],
          },
        ],
        batchName: [
          {
            required: true,
            message: "招生批次不能为空",
            trigger: ["blur", "change"],
          },
        ],
        batchDate: [
          {
            required: true,
            message: "招生截止时间不能为空",
            trigger: ["blur", "change"],
          },
        ],
        educationType: [
          {
            required: true,
            message: "进修形式不能为空",
            trigger: ["blur", "change"],
          },
        ],
        durationName: [
          {
            required: true,
            message: "进修期限不能为空",
            trigger: ["blur", "change"],
          },
        ],
        durationMoney: [
          {
            required: false,
            message: "进修费用不能为空",
            trigger: ["blur", "change"],
          },
        ],
        durationStartDate: [
          {
            required: true,
            message: "进修开始时间不能为空",
            trigger: ["blur", "change"],
          },
        ],
        durationEndDate: [
          {
            required: true,
            message: "进修结束时间不能为空",
            trigger: ["blur", "change"],
          },
        ],
        educationAskObjective: [
          {
            required: true,
            message: "进修要求与目的不能为空",
            trigger: ["blur", "change"],
          },
        ],
        userName: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: ["blur", "change"],
          },
        ],
        gender: [
          {
            required: true,
            type: "number",
            message: "性别不能为空",
            trigger: ["blur", "change"],
          },
        ],
        nation: [
          {
            required: true,
            message: "民族不能为空",
            trigger: ["blur", "change"],
          },
        ],
        profession: [
          {
            required: true,
            message: "从事专业不能为空",
            trigger: ["blur", "change"],
          },
        ],
        politicalOutlook: [
          {
            required: true,
            message: "政治面貌不能为空",
            trigger: ["blur", "change"],
          },
        ],
        healthCondition: [
          {
            required: true,
            message: "健康状况不能为空",
            trigger: ["blur", "change"],
          },
        ],
        technicalTitle: [
          {
            required: true,
            message: "职称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        duties: [
          {
            required: true,
            message: "职务不能为空",
            trigger: ["blur", "change"],
          },
        ],
        idCardType: [
          {
            required: true,
            message: "证件类型不能为空",
            trigger: ["blur", "change"],
          },
        ],
        idCard: [
          {
            required: true,
            message: "证件号码不能为空",
            trigger: ["blur", "change"],
          },
        ],
        birthday: [
          {
            required: true,
            message: "出生日期不能为空",
            trigger: ["blur", "change"],
          },
        ],
        age: [
          {
            required: true,
            type: "number",
            message: "年龄不能为空",
            trigger: ["blur", "change"],
          },
        ],
        highestDegree: [
          {
            required: true,
            message: "最高学历不能为空",
            trigger: ["blur", "change"],
          },
        ],
        graduateSchool: [
          {
            required: true,
            message: "毕业院校不能为空",
            trigger: ["blur", "change"],
          },
        ],
        startWorking: [
          {
            required: true,
            message: "何时参加工作不能为空",
            trigger: ["blur", "change"],
          },
        ],
        doctorCertificateDate: [
          {
            required: true,
            message: "何时获得职业资格证书不能为空",
            trigger: ["blur", "change"],
          },
        ],
        doctorCertificateNumber: [
          {
            required: true,
            message: "资格证书编号不能为空",
            trigger: ["blur", "change"],
          },
        ],
        practicingCertificateNumber: [
          {
            required: true,
            message: "执业证书编号不能为空",
            trigger: ["blur", "change"],
          },
        ],
        operatingDevice: [
          {
            required: true,
            message: "操作设备的名称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        engagedRadiatePost: [
          {
            required: true,
            type: "number",
            message: "是否从事放射诊疗技术岗位不能为空",
            trigger: ["blur", "change"],
          },
        ],
        phoneNumber: [
          {
            required: true,
            message: "手机号码不能为空",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              // 并且得是数字
              const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
              if (!reg.test(value)) {
                callback(new Error("手机号码格式不正确"));
              } else {
                callback();
              }
            },
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不能为空",
            trigger: ["blur", "change"],
          },
        ],
        workTelephone: [
          {
            required: true,
            message: "单位电话不能为空",
            trigger: ["blur", "change"],
          },
        ],
        zipCode: [
          {
            required: true,
            message: "邮编不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitLevel: [
          {
            required: true,
            message: "单位等级不能为空",
            trigger: ["blur", "change"],
          },
        ],
        hospitalLevel: [
          {
            required: true,
            message: "医院级别不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitName: [
          {
            required: true,
            message: "单位名称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitProvince: [
          {
            required: true,
            message: "单位地址(省)不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitCity: [
          {
            required: true,
            message: "单位地址(市)不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitDistrict: [
          {
            required: true,
            message: "单位地址(区)不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitAddress: [
          {
            required: true,
            message: "单位地址(地址)不能为空",
            trigger: ["blur", "change"],
          },
        ],
        politicalRepresentation: [
          {
            required: true,
            message: "政治表现不能为空",
            trigger: ["blur", "change"],
          },
        ],
        proposedMajor: [
          {
            required: true,
            message: "拟进修专业方面的工作基础不能为空",
            trigger: ["blur", "change"],
          },
        ],
        registerApplicationForm: [
          {
            required: true,
            message: "进修申请表不能为空",
            trigger: ["blur", "change"],
          },
        ],
        diploma: [
          {
            required: true,
            message: "毕业证书不能为空",
            trigger: ["blur", "change"],
          },
        ],
        medicalInstitutionLevel: [
          {
            required: true,
            message: "医疗机构等级图片不能为空",
            trigger: ["blur", "change"],
          },
        ],
        qualification: [
          {
            required: true,
            message: "资格证书不能为空",
            trigger: ["blur", "change"],
          },
        ],
        practicingCertificate: [
          {
            required: true,
            message: "执业证书不能为空",
            trigger: ["blur", "change"],
          },
        ],
        practiceResult: [
          {
            required: true,
            message: "执业注册信息查询结果不能为空",
            trigger: ["blur", "change"],
          },
        ],
        professionalTitleCertificate: [
          {
            required: true,
            message: "职称证书不能为空",
            trigger: ["blur", "change"],
          },
        ],
        idCardFront: [
          {
            required: true,
            message: "身份证正面不能为空",
            trigger: ["blur", "change"],
          },
        ],
        idCardBack: [
          {
            required: true,
            message: "身份证背面不能为空",
            trigger: ["blur", "change"],
          },
        ],
        electronicIdPhoto: [
          {
            required: true,
            message: "电子证件照不能为空",
            trigger: ["blur", "change"],
          },
        ],
        otherAttachment: [
          {
            required: false,
            message: "其他补充附件不能为空",
            trigger: ["blur", "change"],
          },
        ],
        auditStatus: [
          {
            required: true,
            message: "审核状态不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      consts: consts,
      noticeShow: false,
      finishShow: false,
      submitLoading: false,
      month: 1,
    };
  },
  created() {
    this.form.registerYear = new Date().getFullYear();
    // this.getRegisterInfo(this.$route.query.id)
    this.listAllRegisterDept();
  },
  methods: {
    durationNameChange(e) {
      for (let i = 0; i < this.durationNameList.length; i++) {
        let item = this.durationNameList[i];
        if (e == item.name) {
          this.form.durationMoney = item.money;
          break;
        }
      }
      this.handleDurationDate();
    },
    batchNameChange(e) {
      if (!e) {
        this.batchNameObj = null;
        this.form.batchDate = "";
        this.alertMsg = "";
        this.handleDurationDate();
        return;
      }
      let matched = false;
      for (let i = 0; i < this.batchNameList.length; i++) {
        let item = this.batchNameList[i];
        if (e == item.name) {
          matched = true;
          this.batchNameObj = item;
          this.form.batchDate = item.date;
          if (item.year) {
            this.currYear = item.year;
            this.form.registerYear = item.year;
          } else if (this.form.registerYear) {
            this.currYear = this.form.registerYear;
          } else {
            this.currYear = new Date().getFullYear();
            this.form.registerYear = this.currYear;
          }
          const deadlineDate = this.extractBatchDeadline(item.date);
          this.alertMsg = deadlineDate
            ? `该批次进修报名截止时间：${deadlineDate}`
            : "";
          break;
        }
      }
      if (!matched) {
        this.alertMsg = "";
      }
      this.handleDurationDate();
    },
    extractBatchDeadline(dateRange) {
      if (!dateRange) {
        return "";
      }
      let endDateStr = "";
      if (dateRange.includes("~")) {
        endDateStr = dateRange.split("~")[1];
      } else {
        const timeRangeReg =
          /^(.+?\d{2}:\d{2}:\d{2})\s*[-~]\s*(.+?\d{2}:\d{2}:\d{2})$/;
        const match = dateRange.match(timeRangeReg);
        if (match) {
          endDateStr = match[2];
        } else if (dateRange.includes("-")) {
          const parts = dateRange.split("-");
          endDateStr = parts[parts.length - 1];
        } else {
          endDateStr = dateRange;
        }
      }
      if (!endDateStr) {
        return "";
      }
      const dateOnly = endDateStr.trim().split(" ")[0];
      return dateOnly.replace(/-/g, "/");
    },
    // 计算进修开始、结束时间
    handleDurationDate() {
      console.log("handleDurationDate", this.form);
      if (!this.form.batchName || !this.form.durationName) {
        this.durationDateList = [];
        return;
      }
      const monthToDate = {
        "1月": "/01",
        "2月": "/02",
        "3月": "/03",
        "4月": "/04",
        "5月": "/05",
        "6月": "/06",
        "7月": "/07",
        "8月": "/08",
        "9月": "/09",
        "10月": "/10",
        "11月": "/11",
        "12月": "/12",
      };
      const batchMonth = this.form.batchName.replace("份", "");
      const monthStr = monthToDate[batchMonth];
      if (!monthStr) {
        this.durationDateList = [];
        return;
      }
      const startDate = this.currYear + monthStr;
      this.form.durationStartDate = startDate;

      // 兼容苹果日期格式
      const formatDateForSafari = (dateStr) => dateStr.replace(/-/g, "/");

      // 按天计算结束时间
      if (this.form.durationName.indexOf("天") > -1) {
        let time = startDate;
        if (time.length == 7) {
          time = time + "/01";
        }
        let date = new Date(formatDateForSafari(time));
        date.setDate(
          date.getDate() + parseInt(this.form.durationName.replaceAll("天", ""))
        );
        this.form.durationEndDate = date
          .toISOString()
          .slice(0, 10)
          .replace(/-/g, "/");
        this.durationDateList = [
          this.form.durationStartDate,
          this.form.durationEndDate,
        ];
        this.durationNameType = 2;
        return;
      }
      let time = startDate;
      if (time.length == 7) {
        time = time + "/01";
      }
      // 按月计算结束时间
      let date = new Date(formatDateForSafari(time));
      date.setMonth(
        date.getMonth() + Number(this.form.durationName.replace("个月", ""))
      );
      this.form.durationEndDate = date
        .toISOString()
        .slice(0, 7)
        .replace("-", "/");
      this.durationDateList = [
        this.form.durationStartDate,
        this.form.durationEndDate,
      ];
      console.log(this.durationDateList);
      this.durationNameType = 1;
    },
    isCurrDateRange(dateStr) {
      if (!dateStr) return true;

      let startStr = "";
      let endStr = "";

      if (dateStr.includes("~")) {
        [startStr, endStr] = dateStr.split("~");
      } else {
        const rangeWithTime = dateStr.match(
          /^(.+?\d{2}:\d{2}:\d{2})\s*-\s*(.+?\d{2}:\d{2}:\d{2})$/
        );
        if (rangeWithTime) {
          startStr = rangeWithTime[1];
          endStr = rangeWithTime[2];
        } else {
          const roughParts = dateStr.split("-");
          if (roughParts.length >= 2) {
            startStr = roughParts[0];
            endStr = roughParts[roughParts.length - 1];
          } else {
            return true;
          }
        }
      }

      const normalizeDate = (str) => {
        if (!str) return null;
        const dateOnly = str.trim().split(" ")[0];
        return new Date(dateOnly.replace(/-/g, "/"));
      };

      const startDate = normalizeDate(startStr);
      const endDate = normalizeDate(endStr);
      if (!startDate || !endDate || isNaN(startDate) || isNaN(endDate)) {
        return true;
      }

      endDate.setHours(23, 59, 59, 999);
      const currentDate = new Date();
      return currentDate >= startDate && currentDate <= endDate;
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    getInfo(e) {
      if (e) {
        this.form.registerDeptName = this.registerDeptList.find(
          (item) => item.id === e
        ).registerDeptName;
      } else {
        this.form.registerDeptName = "";
        this.batchNameList = [];
        this.durationNameList = [];
        this.form.batchName = "";
        this.form.durationName = "";
        this.alertMsg = "";
        return;
      }
      listRegisterNeed({
        registerDeptId: this.form.registerDeptId,
      }).then((response) => {
        if (!response.rows.length) {
          this.batchNameList = [];
          this.durationNameList = [];
          this.form.batchName = "";
          this.form.durationName = "";
          this.alertMsg = "";
          return;
        }
        const data = response.rows[0];
        this.batchList = data.batchNameList.split(",");
        const needNameList = data.needNameList
          ? data.needNameList.split(",")
          : [];
        let batchNameList = [];
        if (data.batchDateList) {
          const batchDateList = data.batchDateList.split(",");
          for (let i = 0; i < this.batchList.length; i++) {
            let date = batchDateList[i] || "";
            batchNameList.push({
              name: this.batchList[i],
              date: date,
              year: needNameList[i]
                ? needNameList[i].toString().trim()
                : "",
              useStatus: this.isCurrDateRange(date),
            });
          }
        }
        this.batchNameList = batchNameList;
        if (this.batchNameList.length > 0) {
          let item = this.batchNameList.find((e) => e.useStatus);
          if (item) {
            this.form.batchName = item.name;
          } else {
            this.form.batchName = this.batchNameList[0].name;
          }
          this.batchNameChange(this.form.batchName);
        }

        this.durationList = data.durationNameList.split(",");
        let durationNameList = [];
        const durationMoneyList = data.durationMoneyList
          ? data.durationMoneyList.split(",")
          : [];
        for (let i = 0; i < this.durationList.length; i++) {
          durationNameList.push({
            name: this.durationList[i],
            money: durationMoneyList[i] || "",
          });
        }
        this.durationNameList = durationNameList;
        if (this.durationNameList.length > 0) {
          this.form.durationName = this.durationNameList[0].name;
          this.durationNameChange(this.form.durationName);
        }
        this.handleDurationDate();
      });
    },
    // 进修时间
    durationDateChange() {
      if (this.durationDateList.length == 2) {
        this.form.durationStartDate = this.durationDateList[0];
        this.form.durationEndDate = this.durationDateList[1];
      }
    },
    // 下一步
    stepActiveNext() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.stepActive == 2) {
            if (this.form.registerLearnVoList.length == 0) {
              this.$modal.msgError("请添加学习经历");
              return;
            } else {
              for (let i = 0; i < this.form.registerLearnVoList.length; i++) {
                let item = this.form.registerLearnVoList[i];
                if (
                  isEmpty(item.startDate) ||
                  isEmpty(item.endDate) ||
                  isEmpty(item.schoolName) ||
                  isEmpty(item.professionName) ||
                  isEmpty(item.designationName) ||
                  isEmpty(item.education) ||
                  isEmpty(item.academicDegree)
                ) {
                  this.$modal.msgError("请完善第" + (i + 1) + "条学习经历");
                  return;
                }
              }
            }
            if (this.form.registerLearnVoList.length == 0) {
              this.$modal.msgError("请添加工作经历");
              return;
            } else {
              for (let i = 0; i < this.form.registerWorkVoList.length; i++) {
                let item = this.form.registerWorkVoList[i];
                if (
                  isEmpty(item.startDate) ||
                  isEmpty(item.endDate) ||
                  isEmpty(item.hospitalName) ||
                  isEmpty(item.deptName) ||
                  isEmpty(item.technicalTitle) ||
                  isEmpty(item.duties)
                ) {
                  this.$modal.msgError("请完善第" + (i + 1) + "条工作经历");
                  return;
                }
              }
            }
            if (this.form.registerLearnVoList.length == 0) {
              this.$modal.msgError("请添加外语水平");
              return;
            } else {
              for (
                let i = 0;
                i < this.form.registerLanguageVoList.length;
                i++
              ) {
                let item = this.form.registerLanguageVoList[i];
                if (
                  isEmpty(item.languages) ||
                  isEmpty(item.literacy) ||
                  isEmpty(item.listenAndSpeak)
                ) {
                  this.$modal.msgError("请完善第" + (i + 1) + "条外语水平");
                  return;
                }
              }
            }
            this.stopForm();
          } else {
            this.stepActive++;
          }
          window.scrollTo({ top: 0, behavior: "smooth" });
        } else {
          this.$modal.msgError("请先完善表单信息");
        }
      });
    },
    // 学习经历
    registerLearnAdd() {
      let i = this.form.registerLearnVoList.length;
      if (i > 0) {
        let item = this.form.registerLearnVoList[i - 1];
        if (
          isEmpty(item.startDate) ||
          isEmpty(item.endDate) ||
          isEmpty(item.schoolName) ||
          isEmpty(item.professionName) ||
          isEmpty(item.designationName) ||
          isEmpty(item.education) ||
          isEmpty(item.academicDegree)
        ) {
          this.$modal.msgError("请完善第" + i + "条学习经历");
          return;
        }
      }
      this.form.registerLearnVoList.push({
        // id: null,
        // registerId: null,
        startDate: null,
        endDate: null,
        schoolName: null,
        professionName: null,
        designationName: null,
        education: null,
        academicDegree: null,
      });
    },
    registerLearnDelete(index) {
      this.form.registerLearnVoList.splice(index, 1);
    },
    // 工作经历
    registerWorkAdd() {
      let i = this.form.registerWorkVoList.length;
      if (i > 0) {
        let item = this.form.registerWorkVoList[i - 1];
        if (
          isEmpty(item.startDate) ||
          isEmpty(item.endDate) ||
          isEmpty(item.hospitalName) ||
          isEmpty(item.deptName) ||
          isEmpty(item.technicalTitle) ||
          isEmpty(item.duties)
        ) {
          this.$modal.msgError("请完善第" + i + "条工作经历");
          return;
        }
      }
      this.form.registerWorkVoList.push({
        // id: null,
        // registerId: null,
        startDate: null,
        endDate: null,
        hospitalLevel: null,
        hospitalName: null,
        deptName: null,
        technicalTitle: null,
        duties: null,
      });
    },
    registerWorkDelete(index) {
      this.form.registerWorkVoList.splice(index, 1);
    },
    // 外语水平
    registerLanguageAdd() {
      let i = this.form.registerLanguageVoList.length;
      if (i > 0) {
        let item = this.form.registerLanguageVoList[i - 1];
        if (
          isEmpty(item.languages) ||
          isEmpty(item.literacy) ||
          isEmpty(item.listenAndSpeak)
        ) {
          this.$modal.msgError("请完善第" + i + "条外语水平");
          return;
        }
      }
      this.form.registerLanguageVoList.push({
        // id: null,
        // registerId: null,
        languages: null,
        literacy: null,
        listenAndSpeak: null,
      });
    },
    registerLanguageDelete(index) {
      this.form.registerLanguageVoList.splice(index, 1);
    },
    // 查询报名信息
    async getRegisterInfo(id) {
      await getRegisterInfo(id).then((response) => {
        this.form = response.data;
        this.getInfo(this.form.registerNeedId);
      });
    },
    stopForm() {
      this.form.auditStatus = 0;
      this.saveForm();
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.auditStatus = 1;
          this.saveForm();
        } else {
          this.noticeShow = false;
          this.submitLoading = false;
          this.$modal.msgError("请先完善表单信息");
        }
      });
    },
    saveForm() {
      this.submitLoading = true;
      agentRegisterInfo(this.form)
        .then((response) => {
          this.submitLoading = false;
          if (this.form.auditStatus == 0) {
            this.$modal.msgSuccess("暂存成功");
            if (this.stepActive == 2) {
              this.stepActive++;
            }
          } else {
            this.finishShow = true;
            this.$modal.msgSuccess("提交成功");
          }
        })
        .catch(() => {
          this.submitLoading = false;
        });
    },
    // 下载申请表模板
    downloadApplyTemplate() {
      addRegisterInfo(this.form).then(async (response) => {
        await this.getRegisterInfo(response.data);
        // window.location.href = this.baseUrl + '/business/registerPerson/downloadApplyTemplate?id=' + this.form.id
        this.$loading({
          lock: true,
          text: "下载中,请稍等",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)",
        });

        fetch(
          this.baseUrl +
            "/business/registerPerson/downloadApplyTemplate?id=" +
            this.form.id
        )
          .then((response) => response.blob())
          .then((blob) => {
            const a = document.createElement("a");
            const objectUrl = URL.createObjectURL(blob);
            a.href = objectUrl;
            a.download = "进修申请表.pdf";
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(objectUrl);
          })
          .finally(() => {
            this.$loading().close();
          });
      });
    },
    finishSuccess() {
      this.$router.push("/apply");
    },
    finishCancel() {
      this.$router.push("/");
    },
  },
};
</script>

<style lang="scss" scoped>
.main2-container {
  width: 1200px;
  margin-left: calc((100% - 1200px) / 2);
  margin-top: 15px;
  margin-bottom: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 5px 5px 10px 0 rgba(157, 156, 156, 0.1);
}

.header-title {
  background-color: #eee;
  height: 50px;
  line-height: 50px;
  font-weight: bolder;
  font-size: 18px;
  padding-left: 15px;
  border-left: 6px solid #a52529;
  border-radius: 5px;
  margin-bottom: 15px;
  display: flex;

  .desc {
    font-size: 16px;
    font-weight: normal;

    .red {
      color: #a52529;
    }
  }

  .download {
    color: #409eff;
    font-size: 16px;
    font-weight: normal;
    cursor: pointer;
  }
}

.image-box {
  padding-bottom: 0;
}

.item-box {
  border-bottom: 3px dotted #ebeef5;
  margin-bottom: 15px;
  padding-bottom: 15px;
}

.notice {
  .title {
    margin-top: 15px;
    font-size: 28px;
    font-weight: 600;
    color: #333;
  }

  .content {
    font-size: 20px;
    text-align: center;
    margin-top: -10px;
    border-top: 3px dotted #ebeef5;
    border-bottom: 3px dotted #ebeef5;
    padding: 20px;
    color: rgb(51, 51, 51);
    line-height: 36px;
  }
}

.bottom-box {
  margin-top: 15px;
  margin-bottom: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 10px;
  text-align: center;
}

.batch-select-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
}

.batch-select-wrapper .batch-select {
  flex: 1;
}

.batch-deadline-tip {
  margin-left: 12px;
  color: #f56c6c;
  font-size: 12px;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.batch-deadline-tip i {
  margin-right: 4px;
  font-size: 14px;
}
</style>
